package webbandidong.validator;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import webbandidong.bo.AdminBO;
import webbandidong.model.Admin;
import webbandidong.util.Constant;
import webbandidong.viewmodel.AdminLoginViewModel;

public class AdminLoginValidator implements Validator {

    @Autowired
    private AdminBO adminBO;

    public void setAdminBOImpl(AdminBO adminBO) {
        this.adminBO = adminBO;
    }

    public boolean supports(Class clazz) {
        return AdminLoginViewModel.class.isAssignableFrom(clazz);
    }

    public void validate(Object target, Errors errors) {
        ValidationUtils.rejectIfEmpty(errors, "username", "required.username", "Username is required");
        AdminLoginViewModel model = (AdminLoginViewModel)target;
        if (Constant.MD5_EMPTY_PASSWORD.equals(model.getPassword())) {
            errors.rejectValue("password", "required.password");
        }
        if (!errors.hasErrors()) {
            Admin admin = new Admin(0, model.getUsername(), model.getPassword());
            String status = adminBO.checkExists(admin);
            if ("".equals(status)) {
                errors.reject("login.failure");
            }
            else if (Constant.ERROR.equals(status)) {
                errors.reject("unexpected.failure");
            }
        }
    }
}
